import java.util.ArrayList;
import java.util.List;

public class GenerateParenthesis {
    // leetcode 括号生成
    // https://leetcode.cn/problems/generate-parentheses/description/?envType=study-plan-v2&envId=top-100-liked
    List<String> ret;
    StringBuilder path;
    int left, right;
    public List<String> generateParenthesis(int n) {
        ret = new ArrayList<>();
        path = new StringBuilder();
        backTracing(n);
        return ret;
    }

    private void backTracing(int n) {
        if (left == n && right == n) {
            ret.add(path.toString());
            return;
        }
        if (left < n) {
            path.append("(");
            left++;
            backTracing(n);
            path.deleteCharAt(path.length() - 1);
            left--;
        }
        if (right < left) {
            path.append(")");
            right++;
            backTracing(n);
            path.deleteCharAt(path.length() - 1);
            right--;
        }
    }
}
